const ctxPath = document.getElementById("ctxPath").value;
Vue.config.productionTip = false

import batchUtil from "../util/batchUtil.js";

new Vue({
    el: '#app',
    components: {
        batchUtil
    },
    data() {
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                // const checkPwd = new RegExp('(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]).{8,20}');
                // if (!checkPwd.test(value)) {
                //     callback(new Error('密码复杂度太低（密码需包含大小写字母、数字及特殊字符组合且不少于8位），请重新输入！'));
                // }
                if (this.addUserForm.checkPass !== '') {
                    this.$refs.addUserForm.validateField('checkPass');
                }
                callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.addUserForm.password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        var addUserAccountValid = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else{
                $.ajax({
                    type: "post",
                    url: ctxPath + "/system/user/isExist",
                    data: "account=" + value,
                    dataType: "json",
                    complete: function (data) {
                        data = data.responseJSON;
                        if(data.code === 200 && data.data === true){
                            callback(new Error('登录账号已经存在!'));
                        }else{
                            callback();
                        }
                    }
                });
            }
        };
        return {
            account: '',
            userName: '',
            role: 0,
            total: 0,
            listData: [],
            currentPage: 1,
            pageSize: 10,
            fileList: [],
            uploadDialog: false,
            uploadUrl: ctxPath + '/system/user/uploadFile',
            exportUrl: ctxPath + "/system/user/exportTemplate",
            form: {
                datemin: '',
                datemax: '',
                keyword: ''
            },
            loading: false,
            accountAttributesOption: [{value: '普通用户', label: '普通用户'},],
            updateUserDialog: false,
            updateUserForm: {
                id: '',
                userName: '',
                password: '',
                rid: '',
                deptName: '电务部',
                sectionName: '',
                workshop: '',
                workArea: '',
                accountAttributes: ''
            },
            updateUserPwd: null,
            updateUserShow:{
                sectionName: true,
                workshop: true,
                workArea: true,
                updateSectionNameShow: true,
                updateworkshopShow: true,
                updateworkAreaShow: true,
            },
            ridOption:[],
            sectionNameOption:[],
            workshopOption:[],
            workAreaOption:[],
            updateUserRules: {
                accountAttributes: {required: true, message: '请选择用户角色', trigger: 'blur'},
                userName: {required: true, message: '请输入用户名称', trigger: 'blur'},
                password: {required: true, message: '请输入用户密码', trigger: 'blur'},
                sectionName: [
                    { required: true, message: '站段不能为空', trigger: 'change',
                        validator: (rule, value, callback) => {
                            if (['站段', '车间', '工区'].includes(this.updateUserForm.accountAttributes) && !value) {
                                callback(new Error('站段不能为空'))
                            } else {
                                callback()
                            }
                        }
                    }
                ],
                workshop: [
                    { required: true, message: '车间不能为空', trigger: 'change',
                        validator: (rule, value, callback) => {
                            if (['车间', '工区'].includes(this.updateUserForm.accountAttributes) && !value) {
                                callback(new Error('车间不能为空'))
                            } else {
                                callback()
                            }
                        }
                    }
                ],
                workArea: [
                    { required: true, message: '工区不能为空', trigger: 'change',
                        validator: (rule, value, callback) => {
                            if (this.updateUserForm.accountAttributes === '工区' && !value) {
                                callback(new Error('工区不能为空'))
                            } else {
                                callback()
                            }
                        }
                    }
                ],
            },
            updatePwdDialog: false,
            updatePwdForm: {
                updateId: '',
                updateAccount: '',
                updatePwd: '',
                checkPass: '',
            },
            updatePwdRules: {
                updatePwd: {required: true, message: '请输入新密码', trigger: 'blur'},
                checkPass: {required: true, message: '请输入确认密码', trigger: 'blur'},
            },
            addUserDialog: false,
            addUserForm: {
                userName: '',
                account: '',
                password: '',
                checkPass: "",
                rid: '',
                deptName: '电务部',
                sectionName: '',
                workshop: '',
                workArea: '',
                accountAttributes: ''
            },
            addUserRules: {
                userName: {required: true, message: '请输入用户名称', trigger: 'blur'},
                account: {required: true, validator: addUserAccountValid, trigger: 'blur'},
                password: [{required: true, validator: validatePass, trigger: 'blur'}],
                checkPass: [{required: true, validator: validatePass2, trigger: 'blur' }],
                // sectionName: [
                //     { required: true, message: '站段不能为空', trigger: 'change',
                //         validator: (rule, value, callback) => {
                //             if (['站段', '车间', '工区'].includes(this.updateUserForm.accountAttributes) && !value) {
                //                 callback(new Error('站段不能为空'))
                //             } else {
                //                 callback()
                //             }
                //         }
                //     }
                // ],
                // workshop: [
                //     { required: true, message: '车间不能为空', trigger: 'change',
                //         validator: (rule, value, callback) => {
                //             if (['车间', '工区'].includes(this.updateUserForm.accountAttributes) && !value) {
                //                 callback(new Error('车间不能为空'))
                //             } else {
                //                 callback()
                //             }
                //         }
                //     }
                // ],
                // workArea: [
                //     { required: true, message: '工区不能为空', trigger: 'change',
                //         validator: (rule, value, callback) => {
                //             if (this.updateUserForm.accountAttributes === '工区' && !value) {
                //                 callback(new Error('工区不能为空'))
                //             } else {
                //                 callback()
                //             }
                //         }
                //     }
                // ],
            },

        }
    },
    created() {
        this.account = $("#account").text();
        this.userName = $("#userName").text();
        this.role = this.account === 'admin' ? 1 : this.account === '管理员' ? 2 : -1;
        if(this.role === 1){
            this.accountAttributesOption = [
                {value: 'admin', label: 'admin'},
                {value: '管理员', label: '管理员'},
                {value: '普通用户', label: '普通用户'},
            ]
        }
        this.queryData();
    },
    updated() {
        //elementui fixed属性会出现表格错误的问题,需要从新渲染
        if (this.$refs.listData && this.$refs.listData.doLayout) {
            this.$refs.listData.doLayout();
        }
    },
    methods: {
        resetForm(){
            this.form = {
                datemin: '',
                datemax: '',
                keyword: ''
            }
        },
        //处理表格序号
        typeIndex(index) {
            return (this.currentPage - 1) * this.pageSize + index + 1;
        },
        // 编写日期格式化方法
        dateFormat: function (row, column) {
            const date = row[column.property]
            if (date === undefined) {
                return ''
            }
            // 这里的格式根据需求修改
            return moment(date).format('YYYY-MM-DD')
        },
        queryData() {
            let me = this;
            me.loading = true;
            let postData = {
                iDisplayStart: me.currentPage,
                iDisplayLength: me.pageSize,
                sSortDir: "desc",
                sSortCol: "createTime",
                datemin: me.form.datemin,
                datemax: me.form.datemax,
                keyword: me.form.keyword,
                other: this.account,
                other2: this.userName
            };
            if(postData.datemax != null && postData != ''){
                postData.datemax +=  " 23:59:59";
            }
            $.ajax({
                type: "post",
                url: ctxPath + "/system/userList",
                data: postData,
                dataType: "json",
                complete: function (data) {
                    data = data.responseJSON;
                    if(data.code === 200){
                        me.listData = data.data.aData;
                        me.total = data.data.iTotalRecords;
                        me.currentPage = 1;
                        me.pageSize = 10;
                        me.loading = false;
                    }
                },
                error: function (data) {
                    me.$message({
                        message: '查询失败',
                        type: 'error',
                        duration: 1000,
                        showClose: true
                    });
                    me.loading = false;
                }
            });
        },
        //导出
        exportData() {
            if (this.form.datemin == null || this.form.datemax == null) {
                this.$message({
                    message: '起始日期或终止日期不能为空',
                    type: 'warning',
                    duration: 1000,
                    showClose: true
                });
                return;
            }
            let datemax = '';
            if(this.form.datemax != null && this.form.datemax != ''){
                datemax =  this.form.datemax + " 23:59:59";
            }
            window.open(ctxPath + "/system/userList/exprotData?datemin=" + this.form.datemin + "&datemax=" + datemax + "&keyword=" + this.form.keyword + "&other=" + this.account);
        },
        //导入
        // 打开上传文件窗口
        uploadDialogOpen(){
            console.log('打开上传文件窗口')
            this.uploadDialog = true;
        },

        //打开修改用户信息窗口
        updateUserOpen(row){
            this.updateUserForm.account = row.account;
            this.updateUserForm.id = row.id;
            this.updateUserForm.userName = row.userName;
            this.updateUserForm.password = row.password;
            this.updateUserPwd = row.password;
            this.updateUserForm.workshop = row.workshop;
            this.updateUserForm.workArea = row.workArea;
            this.updateUserForm.accountAttributes = row.accountAttributes;
            this.updateUserShow.updateSectionNameShow = true;
            this.updateUserShow.updateworkshopShow = true;
            this.updateUserShow.updateworkAreaShow = true;
            let me = this;
            $.ajax({
                type: "post",
                url: ctxPath + "/system/user/getItems",
                data: "colName=cname",
                dataType: "json",
                complete: function (data) {
                    data = data.responseJSON;
                    me.updateUserForm.rid = row.rname == 'admin' ? "2" : row.rid;
                    me.sectionNameOption = data.data;
                    me.sectionNameOption.push({ value: '其他', label: '其他' });
                    me.updateUserForm.sectionName = row.sectionName == undefined ? '' : row.sectionName;
                }
            });
            if(row.sectionName != undefined){
                $.ajax({
                    type: "post",
                    url: ctxPath + "/system/user/getItems",
                    data: "colName=tname&cname=" + row.sectionName,
                    dataType: "json",
                    complete: function (data) {
                        me.workshopOption = data.responseJSON.data;
                        me.workshopOption.push({ value: '其他', label: '其他' });
                    }
                });
            }
            if(row.workshop != undefined){
                $.ajax({
                    type: "post",
                    url: ctxPath + "/system/user/getItems",
                    data: "colName=wname&cname=" + row.sectionName + "&tname=" + row.workshop,
                    dataType: "json",
                    complete: function (data) {
                        me.workAreaOption = data.responseJSON.data;
                        me.workAreaOption.push({ value: '其他', label: '其他' });
                    }
                });
            }
            this.updateUserAccountAttributes(row.accountAttributes);
            this.updateUserDialog = true;
        },
        //账号属性点击事件
        updateUserAccountAttributes(val){
            switch (val) {
                case "电务部":
                    this.updateUserShow.sectionName = false;
                    this.updateUserShow.workshop = false;
                    this.updateUserShow.workArea = false;
                    break;
                case "站段":
                    this.updateUserShow.sectionName = true;
                    this.updateUserShow.workshop = false;
                    this.updateUserShow.workArea = false;
                    break;
                case "车间":
                    this.updateUserShow.sectionName = true;
                    this.updateUserShow.workshop = true;
                    this.updateUserShow.workArea = false;
                    break;
                case "工区":
                    this.updateUserShow.sectionName = true;
                    this.updateUserShow.workshop = true;
                    this.updateUserShow.workArea = true;
                    break;
            }
        },
        //站段下拉框点击事件
        sectionNameSelectChange(val){
            if(val == '其他'){
                this.updateUserForm.sectionName = '';
                this.updateUserShow.updateSectionNameShow = false;
            }
            let me = this;
            $.ajax({
                type: "post",
                url: ctxPath + "/system/user/getItems",
                data: "colName=tname&cname=" + val,
                dataType: "json",
                complete: function (data) {
                    me.workshopOption = data.responseJSON.data;
                    me.workshopOption.push({ value: '其他', label: '其他' });
                    me.updateUserShow.updateworkshopShow = true;
                    me.updateUserForm.workshop = '';
                    me.updateUserForm.workArea = '';
                    me.addUserForm.workshop = '';
                    me.addUserForm.workArea = '';
                }
            });
        },
        //车间下拉框点击事件
        workshopSelectChange(val){
            if(val == '其他'){
                this.updateUserForm.workshop = '';
                this.updateUserShow.updateworkshopShow = false;
            }
            let me = this;
            $.ajax({
                type: "post",
                url: ctxPath + "/system/user/getItems",
                data: "colName=wname&cname=" + me.updateUserForm.sectionName + "&tname=" + val,
                dataType: "json",
                complete: function (data) {
                    me.workAreaOption = data.responseJSON.data;
                    me.workAreaOption.push({ value: '其他', label: '其他' });
                    me.updateUserShow.updateworkAreaShow = true;
                    me.updateUserForm.workArea = '';
                    me.addUserForm.workArea = '';
                }
            });
        },
        //工区下拉框点击事件
        workAreaSelectChange(val) {
            if (val == '其他') {
                this.updateUserForm.workArea = '';
                this.updateUserShow.updateworkAreaShow = false;
            }
        },
        //修改用户信息
        updateUser(formName){
            let me = this;
            var workshop = me.updateUserForm.workshop != undefined ? me.updateUserForm.workshop : '';
            switch (me.updateUserForm.accountAttributes) {
                case "电务部":
                    this.updateUserForm.sectionName = '';
                    this.updateUserForm.workshop = '';
                    this.updateUserForm.workArea = '';
                    break;
                case "站段":
                    this.updateUserForm.workArea = '';
                    break;
                case "车间":
                    this.updateUserForm.workArea = '';
                    break;
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(this.updateUserForm.password == this.updateUserPwd){
                        this.updateUserForm.password = null;
                    }
                    $.ajax({
                        type: "post",
                        url: ctxPath + "/system/user/updateUser",
                        data: this.updateUserForm,
                        dataType: "json",
                        complete: function (data) {
                            data = data.responseJSON;
                            console.log(data);
                            if (data.code === 200 && data.data > 0) {
                                me.$message({
                                    message: '修改成功！',
                                    type: 'success',
                                    duration: 1000,
                                    showClose: true
                                });
                                me.updateUserDialog = false;
                                me.queryData();
                            } else {
                                me.$message.error('修改失败，请联系系统管理员');
                                me.updateUserDialog = false;
                                me.queryData();
                            }
                        },
                        error: function (XmlHttpRequest, textStatus, errorThrown) {
                            console.log("error");
                        },
                    });
                } else {
                    return false;
                }
            });
            me.updateUserForm.workshop = workshop;
        },
        //打开修改用户密码窗口
        updatePwdOpen(id,account){
            this.updatePwdForm.updateAccount = account;
            this.updatePwdForm.updateId = id;
            this.updatePwdDialog = true;
        },
        //关闭修改密码窗口
        updatePwdClose(formName){
            this.updatePwdDialog = false;
            this.$refs[formName].resetFields();
        },
        //修改密码
        updatePwd(formName) {
            let me = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(this.updatePwdForm.updatePwd != this.updatePwdForm.checkPass){
                        this.$message.error('两次输入密码不一致，请重新输入');
                        return;
                    }
                    $.ajax({
                        type: "POST",
                        url: ctxPath + "/system/user/updateUserPwd",
                        data: "id=" + this.updatePwdForm.updateId + '&password=' + this.updatePwdForm.updatePwd,
                        dataType: "json",
                        complete: function (data) {
                            data = data.responseJSON;
                            if (data.code === 200 && data.data === true) {
                                me.$message({
                                    message: '修改成功！',
                                    type: 'success',
                                    duration: 1000,
                                    showClose: true
                                });
                                me.updatePwdForm.updateAccount = '';
                                me.updatePwdForm.updateId = '';
                                me.updatePwdForm.updatePwd = '';
                                me.updatePwdForm.checkPass = '';
                                me.updatePwdDialog = false;
                                me.queryData();
                            } else {
                                me.$message.error('修改密码失败，请联系系统管理员');
                                me.queryData();
                            }
                        },
                        error: function (XmlHttpRequest, textStatus, errorThrown) {
                            console.log("error");
                        },
                    });
                } else {
                    return false;
                }
            });
        },

        //重置密码
        resetPwd(id,account){
            let me = this;
            this.$confirm('确认重置用户[' + account + ']的密码吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                $.ajax({
                    type: "post",
                    url: ctxPath + "/system/user/resetUserPwd",
                    data: "id=" + id,
                    complete: function (data) {
                        data = data.responseJSON;
                        if (data.code === 200 && data.data === true) {
                            me.$message({
                                message: '重置密码成功',
                                type: 'success',
                                duration: 1000,
                                showClose: true
                            });
                            me.queryData();
                        } else {
                            me.$message.error('重置密码失败，请联系系统管理员');
                            me.queryData();
                        }
                    },
                    error: function (XmlHttpRequest, textStatus, errorThrown) {
                        console.log("error");
                    },
                });
            })
        },
        //关闭修改密码窗口
        updateUserClose(formName){
            this.updateUserDialog = false;
            this.$refs[formName].resetFields();
        },
        //打开添加用户窗口
        addUserDialogOpen(){
            let me = this;
            me.updateUserShow.sectionName = false;
            me.updateUserShow.workshop = false;
            me.updateUserShow.workArea = false;
            me.addUserForm.accountAttributes = '普通用户';
            me.addUserDialog = true;
            $.ajax({
                type: "post",
                url: ctxPath + "/system/user/getItems",
                data: "colName=cname",
                dataType: "json",
                complete: function (data) {
                    data = data.responseJSON;
                    me.addUserForm.rid = "999";
                    me.sectionNameOption = data.data;
                    me.sectionNameOption.push({ value: '其他', label: '其他' });
                }
            });

        },
        //添加用户信息
        addUser(formName){
            let me = this;

            this.$refs[formName].validate((valid) => {
                if (valid) {
                    $.ajax({
                        type: "post",
                        url: ctxPath + "/system/user/save",
                        data: this.addUserForm,
                        dataType: "json",
                        complete: function (data) {
                            if (data.responseJSON.code === 200) {
                                me.$message({
                                    message: '添加成功！',
                                    type: 'success',
                                    duration: 1000,
                                    showClose: true
                                });
                                me.addUserDialog = false;
                                me.queryData();
                            } else {
                                me.$message.error('添加失败，请联系系统管理员');
                                me.addUserDialog = false;
                                me.queryData();
                            }
                        },
                        error: function (XmlHttpRequest, textStatus, errorThrown) {
                            console.log("error");
                        },
                    });
                } else {
                    return false;
                }
            });
        },
        //关闭修改密码窗口
        addUserClose(formName){
            this.addUserDialog = false;
            this.$refs[formName].resetFields();
        },
        //修改用户状态/删除
        openData(id,account,type) {
            let me = this;
            if(type != 2){
                const to = type == 1 ? "启用" : "禁用";
                this.$confirm('确认' + to + '用户[' + account + ']吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    $.ajax({
                        type: "GET",
                        url: ctxPath + "/system/user/updateState?id=" + id + "&state=" + type,
                        complete: function (data) {
                            if (data.responseText == 'success') {
                                me.$message({
                                    message: to + '成功',
                                    type: 'success',
                                    duration: 1000,
                                    showClose: true
                                });
                                me.queryData();
                            } else {
                                me.$message.error(to + '失败，请联系系统管理员');
                                me.queryData();
                            }
                        },
                        error: function (XmlHttpRequest, textStatus, errorThrown) {
                            console.log("error");
                        },
                    });
                })
            }else{
                this.$confirm('确认删除用户[' + account + ']吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'error'
                }).then(() => {
                    $.ajax({
                        type: "GET",
                        url: ctxPath + "/system/user/del?id=" + id,
                        complete: function (data) {
                            if (data.responseJSON.code === 200) {
                                me.$message({
                                    message: '删除成功',
                                    type: 'success',
                                    duration: 1000,
                                    showClose: true
                                });
                                me.queryData();
                            } else {
                                me.$message.error('删除失败，请联系系统管理员');
                                me.queryData();
                            }
                        },
                        error: function (XmlHttpRequest, textStatus, errorThrown) {
                            console.log("error");
                        },
                    });
                })
            }
        },
        headStyle() {
            return "font-family: Microsoft YaHei, Microsoft YaHei;\n" +
                "font-weight: bold;\n" +
                "font-size: 14px;\n" +
                "color: #333333;\n" +
                "line-height: 0px;\n" +
                "text-align: center;\n" +
                "font-style: normal;\n" +
                "text-transform: none;background-color:#F6F7FB;"
        },
        rowStyle({row, column, rowIndex, columnIndex}) {
            if (rowIndex % 2 === 0) {
                return "text-align:center;" +
                    "font-family: Microsoft YaHei, Microsoft YaHei;\n" +
                    "font-weight: 400;\n" +
                    "font-size: 14px;\n" +
                    "color: #666666;\n" +
                    "line-height: 0px;\n" +
                    "font-style: normal;\n" +
                    "text-transform: none;"

            } else {
                return "text-align:center;" +
                    "font-family: Microsoft YaHei, Microsoft YaHei;\n" +
                    "font-weight: 400;\n" +
                    "font-size: 14px;\n" +
                    "color: #666666;\n" +
                    "line-height: 0px;\n" +
                    "font-style: normal;\n" +
                    "text-transform: none;background-color:#F6F7FB;"
            }
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.currentPage = 1;
            let me = this;
            me.loading = true;
            let postData = {
                iDisplayStart: 1,
                iDisplayLength: me.pageSize,
                sSortDir: "desc",
                sSortCol: "createTime",
                datemin: me.form.datemin,
                datemax: me.form.datemax,
                keyword: me.form.keyword,
                other: this.account,
                other2: this.userName
            };
            if(postData.datemax != null && postData != ''){
                postData.datemax +=  " 23:59:59";
            }
            $.ajax({
                type: "post",
                url: ctxPath + "/system/userList",
                dataType: "json",
                data: postData,
                complete: function (data) {
                    data = data.responseJSON;
                    if(data.code === 200) {
                        me.listData = data.data.aData;
                        me.loading = false;
                    }
                },
                error: function (data) {
                    me.$message({
                        message: '查询失败',
                        type: 'error',
                        duration: 1000,
                        showClose: true
                    });
                    me.loading = false;
                }
            });
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            val = this.pageSize * val - 1;
            let me = this;
            me.loading = true;
            let postData = {
                iDisplayStart: val,
                iDisplayLength: me.pageSize,
                sSortDir: "desc",
                sSortCol: "createTime",
                datemin: me.form.datemin,
                datemax: me.form.datemax,
                keyword: me.form.keyword,
                other: this.account,
                other2: this.userName
            };
            if(postData.datemax != null && postData != ''){
                postData.datemax +=  " 23:59:59";
            }
            $.ajax({
                type: "post",
                url: ctxPath + "/system/userList",
                dataType: "json",
                data: postData,
                complete: function (data) {
                    data = data.responseJSON;
                    if(data.code === 200) {
                        me.listData = data.data.aData;
                        me.loading = false;
                    }
                },
                error: function (data) {
                    me.$message({
                        message: '查询失败',
                        type: 'error',
                        duration: 1000,
                        showClose: true
                    });
                    me.loading = false;
                }
            });
        },
    }
});